package net.tycmc.bulb.function.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import com.tycmc.functions.util.StringUtil;

public class FilterCharEncoding implements Filter {
	
    protected String encoding = null;

    protected FilterConfig filterConfig = null;
    private String[] ignoreURL = null;
    /**
     * 无须权限控制URL
     */
    public void destroy() {
        this.encoding = null;
        this.filterConfig = null;
    }

    @SuppressWarnings("unchecked")
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
    	/**
		 * 编码转换
		 */
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse res = (HttpServletResponse)response;
		response.setContentType("text/html; charset="+encoding);
		if (req.getMethod().equalsIgnoreCase("post")) {
			try {
				String encoding = this.encoding;
				if (encoding != null){
					request.setCharacterEncoding(encoding);
					response.setCharacterEncoding(encoding);
				}
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}else{
			req = new MyRequest(req);
		}
		
		//访问权限控制------------------------------------------------------------开始
		chain.doFilter(req, response);
	}

	/**
    
    /**
     * Place this filter into service.
     *
     * @param filterConfig The filter configuration object
     */
	public void init(FilterConfig filterConfig) throws ServletException {

		this.filterConfig = filterConfig;
		this.encoding = filterConfig.getInitParameter("encoding");
		String urlValue =  filterConfig.getInitParameter("ignoreURL");
		//不做权限校验的页面
		if(urlValue == null){
			this.ignoreURL=new String[0];
		}else{
			this.ignoreURL=urlValue.split(",");
		}
	
	}
}
